const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");

router.post('/sale/phg', async ctx => {
    try {
        let user = ctx.user;
        let tenantId = user.tenantId;
        let formData = ctx.request.body.formData
        let beginDate = formData.beginDate?formData.beginDate:'200-01-01'
        let endDate = formData.endDate?formData.endDate:tool.getDay()
        let gpType = formData.gpType
        if(gpType === '按商品') {
            let invId = formData.invId
            let inv = ''
            if(invId) inv += ` and invId=${invId} `
            let sql = `
                select invName, sum(qty) qtys,sum(amount) amount 
                from v_sale_gp_cus where tenantId=${tenantId} and billDate between '${beginDate}' and '${endDate}'  ${inv}
                 group by  invName 
            `
            let ret = await db.query(sql, {type: QueryTypes.SELECT})
            return ctx.suc('', {
                total: 0,
                list: ret
            })
        }
        else {
            let buId = formData.buId
            let bu = ''
            if(buId) bu += ` and buId = ${buId} `
            let sql = `
                select buName,sum(qty) qtys,sum(amount) amount  
                from v_sale_gp_cus where tenantId=${tenantId} and billDate between '${beginDate}' and '${endDate}'  
                    ${bu} group by buName
            `
            let ret = await db.query(sql, {type: QueryTypes.SELECT})
            return ctx.suc('', {
                total: 0,
                list: ret
            })
        }
    }
    catch (e) {
        return ctx.err('查询失败')
    }
})

module.exports = router;
